package com.linkhub.oms.component.redis.operator;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.linkhub.oms.common.util.QtStreamUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @Description: redis通用操作
 * @Author: echo
 * @Date: 2024/3/3 11:29
 * @Version: 1.0
 */
@Slf4j
public class QtRedisOperations {

    protected RedisTemplate<String, Object> redisTemplate;
    protected HashOperations<String, Object, Object> defaultHashOperations;

    public QtRedisOperations(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.defaultHashOperations = this.redisTemplate.opsForHash();
    }

    /**
     * 释放分布式锁的脚本
     */
    private static final String UNLOCK_LUA = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then return redis.call(\"del\",KEYS[1]) else return 0 end";

    /**
     * 执行lua脚本
     *
     * @param luaScript lua脚本
     * @return
     * @author lingbiaokong
     */
    public void execute(String luaScript, List<String> keys) {
        redisTemplate.execute(RedisScript.of(luaScript), keys);
    }

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error("RedisOperator expire error:",e);
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    @SuppressWarnings("unchecked")
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error("RedisOperator hasKey... error:",e);
        }
        return false;
    }


    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public String get(String key) {
        return key == null ? null : (String) redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error("RedisOperator set... error:",e);
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key, String value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error("RedisOperator set... error:",e);
            return false;
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        Long increment = redisTemplate.opsForValue().increment(key, delta);
        if (increment != null) {
            return increment;
        }else {
            throw new RuntimeException("incr key is not exist");
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @param time 秒
     * @return
     */
    public long incr(String key, long delta, long time) {
        if (delta < 0) {
            throw new IllegalArgumentException("递增因子必须大于0");
        }
        Long increment = redisTemplate.opsForValue().increment(key, delta);
        expire(key, time);
        if (increment != null) {
            return increment;
        }else {
            throw new IllegalArgumentException("incr key is not exist");
        }
    }

    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     * @return
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        Long increment = redisTemplate.opsForValue().increment(key, -delta);
        if (increment != null) {
            return increment;
        }else {
            throw new RuntimeException("decr key is not exist");
        }
    }


    //===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束  0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            log.error("RedisOperator lGet... error:",e);
            return Collections.emptyList();
        }
    }


    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            log.error("RedisOperator lGetListSize... error:",e);
            return 0;
        }
    }


    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引  index>=0时， 0 表头，1 第二个元素，依次类推；index<0时，-1，表尾，-2倒数第二个元素，依次类推
     * @return
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            log.error("RedisOperator lGetIndex... error:",e);
            return null;
        }
    }


    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            log.error("RedisOperator lUpdateIndex... error:",e);
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key, long count, Object value) {
        try {
            return redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception e) {
            log.error("RedisOperator lRemove... error:",e);
            return 0;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().leftPush(key, value);
            return true;
        } catch (Exception e) {
            log.error("RedisOperator lSet... error:",e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().leftPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("RedisOperator lSet... error:",e);
            return false;
        }
    }

    /**
     * 放入多个值到list
     * @param key
     * @param time
     * @param values
     * @return
    */
    public boolean lSetAll(String key, long time, Object... values) {
        try {
            this.redisTemplate.opsForList().leftPushAll(key, values);
            if (time > 0L) {
                this.expire(key, time);
            }

            return true;
        } catch (Exception var6) {
            log.error("RedisOperator lSetAll... error:", var6);
            return false;
        }
    }

    /**
     * 移除list最右侧一个元素
     *
     * @param key 键
     * @return
     */
    public boolean rPop(String key) {
        try {
            redisTemplate.opsForList().rightPop(key);
            return true;
        } catch (Exception e) {
            log.error("RedisOperator rPop... error:",e);
            return false;
        }
    }

    // ============================set=============================

    public Long sSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            log.error("RedisOperator sSize... error:",e);
            return -1L;
        }
    }
    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            log.error("RedisOperator sGet... error:",e);
            return Collections.emptySet();
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            log.error("RedisOperator sHasKey... error:",e);
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            log.error("RedisOperator sSet... error:",e);
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            log.error("RedisOperator sSetAndTime... error:",e);
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            log.error("RedisOperator sGetSetSize... error:",e);
            return 0;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().remove(key, values);
        } catch (Exception e) {
            log.error("RedisOperator setRemove... error:",e);
            return 0;
        }
    }

    //================================Map=================================

    /**
     * HashGet
     *
     * @param key  键
     * @param item 项，必须为String类型
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 获取hashKey对应的所有值
     */
    public List<Object> hvalues(String key) {
        return redisTemplate.opsForHash().values(key);
    }


    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @param fields 集合 hKey
     * @return 对应的多个键值
     */
    public List<Object> hmget(String key, Collection fields) {
        return redisTemplate.opsForHash().multiGet(key,fields);
    }

    /**
     * 获取hashKey对应的所有键
     *
     * @param key 键
     * @return 对应的多个键
     */
    public Set<Object> hkeys(String key) {
        return redisTemplate.opsForHash().keys(key);
    }

    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            log.error("RedisOperator hmset... error:",e);
            return false;
        }
    }

    /**
     * 泛型hash hHSet
     *
     * @param key  键
     * @param map  对应多个键值
     * @param <HV> value类型
     * @return
     */
    public <HV> boolean genericHMSet(String key, Map<String, HV> map) {
        try {
            redisTemplate.<String, HV>opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            log.error("RedisOperator hmset... error:", e);
            return false;
        }
    }

    /**
     * 泛型hash hHSet，指定key过期时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 过期时间
     * @param <HV> value类型
     * @return
     */
    public <HV> boolean genericHMSet(String key, Map<String, HV> map, long time) {
        try {
            redisTemplate.<String, HV>opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("RedisOperator hmset... error:", e);
            return false;
        }
    }

    /**
     * 泛型获取hash指定 {@code fields} 的值, 默认过滤空元素
     *
     * @param key  键
     * @param fields  对应多个键值
     * @param <HV> value类型
     * @return list
     */
    public <HV> List<HV> genericHMGet(String key, Collection<String> fields) {
        return genericHMGet(key, fields, true);
    }

    /**
     * 泛型获取hash指定 {@code fields} 的值
     *
     * @param key             键
     * @param fields             对应多个键值
     * @param filterNullValue 是否过滤空值
     * @param <HV>            value类型
     * @return
     */
    public <HV> List<HV> genericHMGet(String key, Collection<String> fields, boolean filterNullValue) {
        try {
            List<HV> values = redisTemplate.<String, HV>opsForHash().multiGet(key, fields);
            if (filterNullValue) {
                return QtStreamUtil.filter(values, Objects::nonNull);
            }

            return values;
        } catch (Exception e) {
            log.error("RedisOperator multiGet... error:", e);

        }
        return Lists.newArrayList();
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public <V> List<V> genericHVals(String key) {
        List<V> values = Lists.newArrayList();
        try {
            values = redisTemplate.<String, V>opsForHash().values(key);
        } catch (Exception e) {
            log.error("RedisOperator hvals... error:", e);
        }
        return values;
    }

    /**
     * Get entire hash stored at {@code key}.
     *
     * @param key  key
     * @param <HV> hv Type
     * @return map
     */
    public <HV> Map<String, HV> genericEntries(String key) {
        Map<String, HV> res = Maps.newHashMap();
        try {
            res = redisTemplate.<String, HV>opsForHash().entries(key);
        } catch (Exception e) {
            log.error("RedisOperator genericEntries... error:", e);

        }
        return res;
    }


    /**
     * Get size of hash at {@code key}.
     *
     * @param key must not be {@literal null}.
     * @return {@literal null} when used in pipeline / transaction.
     */
    public Long hSize(String key) {
        try {
             return redisTemplate.opsForHash().size(key);
        } catch (Exception e) {
            log.error("RedisOperator hSize... error:", e);

        }

        return 0L;
    }

    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, ? extends Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("RedisOperator hmset... error:",e);
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项，必须为String类型
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            log.error("RedisOperator hset... error:",e);
            return false;
        }
    }

    /**
     * 向一张 hash 表中放入所有 map 数据
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean hsetMap(String key, Map<?, ?> value, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("RedisOperator hPutAll... error:",e);
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("RedisOperator hset... error:",e);
            return false;
        }
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * Description :
     *
     * @param key
     * @return
     * @author caiyiyong@qtrade.com.cn
     * @Date 2019年11月16日 下午3:43:05
     */
    public boolean setNx(String key, String value, Long expireTime) {
        return (Boolean) redisTemplate.execute((RedisCallback<Object>) connection ->{
            Boolean acquire = connection.setNX(key.getBytes(), value.getBytes());
            if (expireTime != null) {
                connection.expire(key.getBytes(), expireTime);
            }
            return acquire;
        });
    }

    public void publishMsg(String channel, String message) {
        if (channel != null && message != null && channel.length() > 0 && message.length() > 0) {
            redisTemplate.convertAndSend(channel, message);
        }
    }

    /**
     * 尝试加锁
     *
     * @param key    前缀
     * @param value  唯一值
     * @param expire 单位毫秒
     * @return
     */
    public boolean tryLock(String key, String value, long expire, TimeUnit unit) {
        try {
            return redisTemplate.opsForValue().setIfAbsent(key, value, expire, unit);
        } catch (Exception e) {
            log.error("set redis Lock occured an exception,redisTemplate={},key={},value={}",redisTemplate,key,value,e);
        }
        return false;
    }

    /**
     * 释放锁
     *
     * @param key
     * @param value
     * @return boolean
     * @since JDK 1.8
     */
    public boolean unLock(String key, String value) {
        List<String> keys = new ArrayList<>();
        List<String> args = new ArrayList<>();
        keys.add(key);
        args.add(value);
        try {
            RedisCallback<Long> callback = connection -> {
                Object nativeConnection = connection.getNativeConnection();
                if (nativeConnection instanceof JedisCluster) {
                    // 集群模式
                    return (Long) ((JedisCluster) nativeConnection).eval(UNLOCK_LUA, keys, args);
                } else if (nativeConnection instanceof Jedis) {
                    // 单机模式
                    return (Long) ((Jedis) nativeConnection).eval(UNLOCK_LUA, keys, args);
                } else {
                    log.error("redis lock model match error ");
                }
                return 0L;
            };
            Long result = redisTemplate.execute(callback);
            return result != null && result > 0;
        } catch (Exception e) {
            log.error("release lock occured an exception", e);
        }
        return false;
    }

    public <T> List<T> pipelineHValues(List<String> hashKeys, Function<Object, List<T>> convertFunc) {
        List<Object> objects = pipelineHValues(hashKeys);
        return QtStreamUtil.filterAndFlatMap(objects, Objects::nonNull, obj -> convertFunc.apply(obj).stream());
    }

    public List<Object> pipelineHValues(List<String> hashKeys) {
        //noinspection unchecked
        return pipelineHValues(hashKeys, redisTemplate.getHashValueSerializer());

    }

    public List<Object> pipelineHValues(List<String> hashKeys, RedisSerializer<?> redisSerializer) {
        //noinspection unchecked
        return redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            for (String hashKey : hashKeys) {

                byte[] rawKey = getHashKeySerializer().serialize(hashKey);
                if (rawKey != null) {
                    connection.hVals(rawKey);
                }
            }
            // must null
            return null;
        }, redisSerializer);

    }

    public RedisSerializer<Object> getHashKeySerializer() {
        //noinspection unchecked
        return (RedisSerializer<Object>) redisTemplate.getHashKeySerializer();
    }

    public <T> T execute(SessionCallback<T> session){
        return redisTemplate.execute(session);
    }

    /**
     * lua脚本执行
     * @param luaScript
     * @param keys
     * @param args
     */
    public  Object execute(String luaScript, List<String> keys, Object... args) {
        return redisTemplate.execute(RedisScript.of(luaScript, String.class), keys, args);
    }


    public <T> List<Object> executePipeline(SessionCallback<T> session){
        return redisTemplate.executePipelined(session);
    }

}
